"""
Created on 21 mrt. 2012

@author: Daan
"""
import __builtin__
import sys

class builtin_open(object):
    """ DOCSTRING """

    def __init__(self, verbose = False):
        self.__verbose = verbose

        def stub_open(name, mode = 'r', *args, **kwargs):
            """ DOCSTRING"""
            if self.__verbose:
                print >> sys.stderr, "\t open(%s,%s)" % (name, mode)
            open(name, mode, *args, **kwargs)

        self.__stub = stub_open

    def open_fixed_ioerror(self, fixedlist):
        """ DOCSTRING """
        open_temp = __builtin__.open
        def stub_open_fixed(name, mode = 'r', *args, **kwargs):
            """ DOCSTRING """
            if name in fixedlist:
                if self.__verbose:
                    print >> sys.stderr, "\t open(%s,%s):IOError" % (name, mode)
                raise IOError("fixed IO error")
            if self.__verbose:
                print >> sys.stderr, "\t open(%s,%s)" % (name, mode)
            return open_temp(name, mode, *args, **kwargs)
        self.__stub = stub_open_fixed
        return self

    def __enter__(self):
        __builtin__.open = self.__stub

    #noinspection PyUnusedLocal
    def __exit__(self, exc_type, exc_val, exc_tb):
        reload(__builtin__)
